#include "database_sqlite3.h"

// 1. 连接数据库
void DataBaseSqlite3::connect_database() {
    QSqlDatabase db = QSqlDatabase::database(); // 如果已连接，直接获取
    if (!db.isOpen()) {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("my_database.db");
        if (!db.open()) {
            qDebug() << "Error: Database connection failed!" << db.lastError();
            return;
        }
    }
}

// 2. 创建数据表
void DataBaseSqlite3::create_database() {
    QSqlQuery query;
    if (!query.exec("CREATE TABLE IF NOT EXISTS photos ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                   "name TEXT NOT NULL, "
                    "image_data BLOB, "
                   "create_time TEXT, "
                    "type_ani_pla TEXT, "
                    "name_ani_pla TEXT, "
                    "detail_ani_pla TEXT, )")) {
        qDebug() << "Error: Failed to create table." << query.lastError();
    }
}

// 3. 插入数据
void DataBaseSqlite3::insert_database(QString imagePath, QByteArray imageData) {
    QSqlQuery query;
    query.prepare("INSERT INTO photos (name, image_data, create_time) VALUES (?, ?, ?)");
    query.addBindValue(imagePath);               // 图片名称
    query.addBindValue(imageData);               // 图片二进制数据
    query.addBindValue(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); // 创建时间

    if (!query.exec()) {
        qDebug() << "Error: Failed to insert image into database!" << query.lastError();
    } else {
        qDebug() << "Image saved to database!";
    }
}



